import React, { useEffect, useState } from 'react'
import PageHeader from '../components/PageHeader'
import { useRouterHook } from '../utils/hooks'
import { getBusinessInfo } from '../utils/api'
import { Grid, Image, Space, Swiper, Divider, List, Card, Button, Tag } from 'antd-mobile'
import { PhonebookOutline, TravelOutline, UserCircleOutline } from 'antd-mobile-icons'
import AMapLoader from "@amap/amap-jsapi-loader";
import { useDispatch, useSelector } from 'react-redux'
import { getBannerListThunk } from '../store/slices/bannerSlice'
import { getDoctorListThunk } from '../store/slices/doctorSlice'
// 导入的是ts类型
import type { AppDispatch, RootState } from '../store'
const baseUrl=import.meta.env.VITE_API_BASE_URL

const Business: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>()
  const bannerList = useSelector((state: RootState) => state.banner.bannerList)
  const doctorList = useSelector((state: RootState) => state.doctor.doctorList)
  let map: any = null;
  const { params: { id }, navigate } = useRouterHook()
  const [info, setInfo] = useState<Partial<BusinessRowType>>({})
  const getBusiness = async (callback: Function) => {
    const { data } = await getBusinessInfo(id)
    if (data.code === 200) {
      setInfo(data.data)
      // 调用回调函数, 实现地图渲染
      callback && callback(data.data)
    }
  }
  // 渲染地图
  const renderMap = (info: any) => {
    const arr = info.lnglat?.split(',')
    var lng = Number(arr[0])
    var lat = Number(arr[1])
    // @ts-ignore
    window._AMapSecurityConfig = {
      securityJsCode: "4ff653f731fed57e02fb5fff066e3d7d",
    };
    AMapLoader.load({
      key: "f8f11a955d8f2e1bc94c4d7edbdef2e2", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    })
      .then((AMap) => {
        map = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 11, // 初始化地图级别
          center: [lng, lat], // 初始化地图中心点位置
        });
        // 创建一个标记对象
        const marker = new AMap.Marker({
          // position: new AMap.LngLat(116.39, 39.9),
          position: new AMap.LngLat(lng, lat),
          offset: new AMap.Pixel(-10, -10),
          icon: baseUrl+"/uploads/marker/marker.png", //添加 icon 图标 URL
          title: info.title,
        });
        // 将标记对象添加到地图中
        map.add(marker);
        var text = new AMap.Text({
          text: info.title, //标记显示的文本内容
          anchor: "center", //设置文本标记锚点位置
          draggable: false, //是否可拖拽
          cursor: "pointer", //指定鼠标悬停时的鼠标样式。
          angle: 0, //点标记的旋转角度
          style: {
            //设置文本样式，Object 同 css 样式表
            "padding": ".75rem 1.25rem",
            "margin-bottom": "5rem",
            "margin-left": "5rem",
            "border-radius": ".25rem",
            "background-color": "white",
            "box-shadow": "0 2px 6px 0 rgba(114, 124, 245, .5)",
            "text-align": "center",
            "font-size": "20px",

          },
          position: [lng, lat], //点标记在地图上显示的位置
        });
        text.setMap(map); //将文本标记设置到地图上
      })
      .catch((e) => {
        console.log(e);
      });

  }
  useEffect(() => {
    // 请求商户信息
    getBusiness(renderMap)
    // 请求轮播图列表
    dispatch(getBannerListThunk(id))
    // 请求医生列表数据
    dispatch(getDoctorListThunk(id))
    return () => {
      map?.destroy();
    };
  }, [])

  return (
    <div>
      <PageHeader>
        <h3>{info.title}</h3>
      </PageHeader>
      <Grid columns={8} style={{ margin: 16 }}>
        <Grid.Item span={2} >
          <Image style={{ borderRadius: '50%' }} width={100} height={100}
            src={`${baseUrl+info.logo}`} />
        </Grid.Item>
        <Grid.Item span={6}>
          <Space direction="vertical" style={{ fontSize: 16 }}>
            <div><UserCircleOutline style={{ fontSize: 22 }} />: {info.legal_person}</div>
            <div>
              <PhonebookOutline style={{ fontSize: 22 }} />: <a href={`tel:${info.phone}`}>{info.phone}</a>
            </div>
            <div>
              <TravelOutline style={{ fontSize: 22 }} />: {info.province}-{info.city}-{info.county}-{info.address}
            </div>
          </Space>
        </Grid.Item>

      </Grid>
      <Divider></Divider>

      <Swiper loop autoplay autoplayInterval={1500}>
        {bannerList.map((item: BannerRowType) => (
          <Swiper.Item key={item.id}>
            <Image style={{ height: 160 }} src={`${baseUrl+item.img}`}></Image>
          </Swiper.Item>
        ))}
      </Swiper>
      <Divider></Divider>
      <List header={<h3>名医推荐</h3>}>
        {doctorList.map((item: DoctorRowType) => (
          <List.Item
            key={item.id}
            prefix={
              <Image
                src={baseUrl + item.avatar}
                style={{ borderRadius: '50%' }}
                fit='cover'
                width={100}
                height={100}
              />
            }
          >
            <Card title={item.name}>
              <Space direction="vertical">
                <div style={{ fontSize: 14 }}>
                  职称: <Tag color='primary'>{item.title}</Tag>
                </div>
                <Space style={{ fontSize: 14 }}> 擅长领域:{item.tags.map((item: any, index: number) => (
                  <Tag color='success' key={index}>{item}</Tag>
                ))}</Space>
                <div style={{ fontSize: 14 }}>
                  所属医疗机构: {item.bus_title}
                </div>
                <div style={{ fontSize: 14 }}>
                  毕业院校: {item.school}
                </div>
                <Space style={{ display: "flex", justifyContent: "flex-end" }}>
                  <Button onClick={() => navigate(`/appointAdd`, { state: { doctorid: item.id } })} shape="rounded" size="mini" color="primary">立即预约</Button>
                  <Button onClick={() => navigate(`/doctor?id=${item.id}`)} shape="rounded" size="mini" color="success">医生主页</Button>
                </Space>
              </Space>
            </Card>
          </List.Item>
        ))}
      </List>
      <Divider></Divider>
      {/* 高德地图 */}
      <div
        id="container"
        style={{ height: "400px" }}
      ></div>
    </div >
  )
}

export default Business